package com.ebelter.btcomlib.models.bluetooth.base;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.os.Build;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IScanCallback;
import com.ebelter.btcomlib.utils.log.LogUtils;
import java.lang.ref.WeakReference;

/**
 * 蓝牙扫描器
 */

public class BlueScan {
    private static final String TAG = "BlueScan";

    private static final int WHAT_SCANBLUETOOTH_TIME_OVER = 20;


    private long mScanTime = 12000;//扫描时间 默认12秒

    private IScanCallback mIScanCallback;//扫描器的回调

    private BluetoothAdapter mBluetoothAdapter;

    public boolean isScaningFlag;//是否正在扫描的标识

    private MyMainHandle myMainHandle;

    private String filterName;//过滤的蓝牙名字

    public void setFilterName(String filterName) {
        this.filterName = filterName;
    }

    /**一般传context*/
    public BlueScan(Object obj) {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        myMainHandle=new MyMainHandle(obj);
    }

    public void setScanTime(int scanTime) {
        this.mScanTime = scanTime;
    }

    public void setScanCallback(IScanCallback mIScanCallback) {
        this.mIScanCallback = mIScanCallback;
    }

    public void startScanBluetoothDevices(IScanCallback mIScanCallback){
        setScanCallback(mIScanCallback);
        beforeScan();
        scanLeDevice(true);
        if (myMainHandle != null) {
            myMainHandle.removeMessages(WHAT_SCANBLUETOOTH_TIME_OVER);
            myMainHandle.sendEmptyMessageDelayed(WHAT_SCANBLUETOOTH_TIME_OVER,mScanTime);
        }
    }
    public void startScanBluetoothDevices(){

        if (isScaningFlag){
            LogUtils.i(TAG,"已经在扫描了，无需重新扫描");
            return;
        }
        beforeScan();
        scanLeDevice(true);
        if (myMainHandle != null) {
            myMainHandle.removeMessages(WHAT_SCANBLUETOOTH_TIME_OVER);
            myMainHandle.sendEmptyMessageDelayed(WHAT_SCANBLUETOOTH_TIME_OVER,mScanTime);
        }
    }

    public void stopScanBluetoothDevices(){
        scanLeDevice(false);
    }

    private void scanLeDevice(boolean enable) {
        if (mBluetoothAdapter==null){
            LogUtils.i(TAG, "你的手机不支持蓝牙设备---return");
            return;
        }
        if (!mBluetoothAdapter.isEnabled()){
            LogUtils.i(TAG, "手机未开启蓝牙开关--return");
            return;
        }
        if (enable) {
            LogUtils.i(TAG, "开始扫描蓝牙设备。。。");
            isScaningFlag = true;
            //android 5.0 以前
            if (Build.VERSION.SDK_INT < 21) {
                 mBluetoothAdapter.startLeScan(mLeScanCallback);
            }else {
                BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
                if (bluetoothLeScanner!=null){
                    bluetoothLeScanner.startScan(mScanCallback);
                }

            }

        } else{
            LogUtils.i(TAG, "停止扫描蓝牙设备");
            isScaningFlag = false;

            //android 5.0 以前
            if (Build.VERSION.SDK_INT < 21) {
                 mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }else {
                BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
                if (bluetoothLeScanner!=null){
                    bluetoothLeScanner.stopScan(mScanCallback);
                }

            }

        }
    }

    public void exitScan(){
        LogUtils.i(TAG,"-------exitScan------");
        if (isScaningFlag){
            if (myMainHandle!=null){
                myMainHandle.removeMessages(WHAT_SCANBLUETOOTH_TIME_OVER);
                myMainHandle.exitHandle();
            }
            scanLeDevice(false);
            if (mIScanCallback!=null){
                LogUtils.i(TAG, "------------overScan()");
                mIScanCallback.overScan();
            }
        }
    }

    private void beforeScan() {
        if (mIScanCallback!=null){
            LogUtils.i(TAG, "------------beforeScan()");
            mIScanCallback.beforeScan();
        }
    }
    private void scanOneDevice(BluetoothDevice device, int rssi, byte[] scanRecord){
        if (mIScanCallback!=null){
            mIScanCallback.scanOneDevice(device,rssi,scanRecord);
        }
    }

    private void overScan() {
        scanLeDevice(false);
        if (mIScanCallback!=null){
            LogUtils.i(TAG, "------------overScan()");
            mIScanCallback.overScan();
        }
    }


    //扫描回调器
    private final BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {

            if (device!=null && !TextUtils.isEmpty(device.getAddress())){
                LogUtils.i(TAG,"---mLeScanCallback--onLeScan:device.name = "+device.getName()+"--address = "+device.getAddress());

                if (TextUtils.isEmpty(device.getName())){//名字都为空的就直接屏蔽掉
                    return;
                }

                if (!TextUtils.isEmpty(filterName)){
                    if (TextUtils.equals(filterName,device.getName())){
                        scanOneDevice(device,rssi,scanRecord);
                    }
                }else {
                    scanOneDevice(device,rssi,scanRecord);
                }

            }
        }
    };

    private final ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            BluetoothDevice device= null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                device = result.getDevice();

            if (device!=null&&!TextUtils.isEmpty(device.getAddress())){
                LogUtils.i(TAG,"---mScanCallback--onScanResult:device.name = "+device.getName()+"--address = "+device.getAddress());

                if (TextUtils.isEmpty(device.getName())){//名字都为空的就直接屏蔽掉
                    return;
                }

                if (!TextUtils.isEmpty(filterName)){
                    if (TextUtils.equals(filterName,device.getName())){

                        if (result.getScanRecord()==null){
                            scanOneDevice(device,result.getRssi(),null);
                        }else {
                            scanOneDevice(device,result.getRssi(),result.getScanRecord().getBytes());
                        }


                    }
                }else {
                    if (result.getScanRecord()==null){
                        scanOneDevice(device,result.getRssi(),null);
                    }else {
                        scanOneDevice(device,result.getRssi(),result.getScanRecord().getBytes());
                    }
                }

            }

            }
        }
    };

    @SuppressLint("HandlerLeak")
    private class MyMainHandle extends android.os.Handler{
        private WeakReference<Object> mWeakReference;

        MyMainHandle(Object obj){
            super(Looper.getMainLooper());
            mWeakReference = new WeakReference<>(obj);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mWeakReference==null||mWeakReference.get()==null){
                return;
            }
            LogUtils.i(TAG,Thread.currentThread().getName()+"--MyMainHandle()--msg.what"+msg.what);
            switch (msg.what){
                case WHAT_SCANBLUETOOTH_TIME_OVER:
                    overScan();
                    break;
            }
        }
        private void exitHandle(){
            removeCallbacksAndMessages(null);
            if (mWeakReference!=null){
                mWeakReference.clear();
                mWeakReference=null;
            }
        }
    }


    public void realse(){
        stopScanBluetoothDevices();
        if (myMainHandle!=null){
            myMainHandle.exitHandle();
            myMainHandle=null;
        }

    }


}
